package gae.twitter.controller;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

import com.google.gdata.client.GoogleService;
import com.google.gdata.data.Category;
import com.google.gdata.data.Entry;
import com.google.gdata.data.Feed;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

@Component
@Controller
public class Backup2Blogspot {
	private static final Logger logger = Logger.getLogger(Backup2Blogspot.class.getName());
	
	private final String notifierPath = "http://url-services.appspot.com/NotifierServlet?msg=";
    private final String getUrl = "http://www.blogger.com/feeds/7654023/posts/default?category=tweet&orderby=updated";
    private final String postUrl = "http://www.blogger.com/feeds/7654023/posts/default";
            
    @Value("${gae.twitter.controller.Backup2Blogspot.gUsername}")    
    private String gUsername;
    
    @Value("${gae.twitter.controller.Backup2Blogspot.gPassword}")
    private String gPassword;    
    
    @Value("${gae.twitter.controller.Backup2Blogspot.tUsername}")
    private String tUsername;
    
    @Value("${gae.twitter.controller.Backup2Blogspot.tConsumerKey}")
    private String tConsumerKey;
    
    @Value("${gae.twitter.controller.Backup2Blogspot.tConsumerSecret}")
    private String tConsumerSecret;
    
    @Value("${gae.twitter.controller.Backup2Blogspot.tAccessToken}")
    private String tAccessToken;
    
    @Value("${gae.twitter.controller.Backup2Blogspot.tAccessTokenSecret}")
    private String tAccessTokenSecret;
    
		
    @RequestMapping(value = "/backup2blogspot", method = RequestMethod.GET)
    public ModelAndView anyMethodName() throws IOException {
    	GoogleService myService = new GoogleService("blogger", "Backup2Blogspot");
        int posted = 0;
        try {
            myService.setUserCredentials(gUsername, gPassword);
            URL feedUrl = new URL(getUrl);
            Feed resultFeed = myService.getFeed(feedUrl, Feed.class);

            long startPostID = 0;
            if (resultFeed.getEntries().size() > 0) {
                Entry entry = resultFeed.getEntries().get(0);
                startPostID = Long.parseLong(entry.getTitle().getPlainText());
            }
            //startPostID = 14596788878L;
            logger.info("startPostID="+String.valueOf(startPostID));
            logger.info("==== start posting ====");

            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey(tConsumerKey)
                                       .setOAuthConsumerSecret(tConsumerSecret)
                                       .setOAuthAccessToken(tAccessToken)
                                       .setOAuthAccessTokenSecret(tAccessTokenSecret);
            
            TwitterFactory factory = new TwitterFactory(cb.build());
            Twitter twitter = factory.getInstance();
            
            List<Status> statuses = twitter.getUserTimeline(tUsername);
            logger.info("size=" + statuses.size());
            for (int i = statuses.size()-1; i>=0; i--) {
                Status status = statuses.get(i);
                if (status.getId() > startPostID) {
                    posted++;
                    //System.out.println(status.getUser().getName() + "@" + status.getId() + "\t"+ status.getCreatedAt() + "\t" + status.getText() );
                    
                    String geoLocation = (status.getGeoLocation() != null) ? status.getGeoLocation().toString() : "";
                    logger.info(status.getUser().getName() + "@" + status.getId() + "\t"+ status.getCreatedAt() + "\t" + status.getText() + "\t" + geoLocation);
                    
                    Entry myEntry = new Entry();
                    myEntry.setTitle(new PlainTextConstruct(String.valueOf(status.getId())));
                    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    myEntry.setContent(new PlainTextConstruct(
                            "<a href='http://twitter.com/bansiudou/status/" + status.getId() + "'>" + format.format(status.getCreatedAt()) + "</a>"
                            + " " + change2Href(status.getText())
                            + " " + geoLocation)
                    );
                    Category category = new Category();  
                    category.setScheme("http://www.blogger.com/atom/ns#");
                    category.setTerm("tweet"); 
                    URL pUrl = new URL(postUrl);
                    myEntry.getCategories().add(category); 
                    myService.insert(pUrl, myEntry);
                }
                
            }
        } catch (AuthenticationException e) {
            logger.info(e.getMessage());
            e.printStackTrace();
        } catch (ServiceException e) {
            logger.info(e.getMessage());
            e.printStackTrace();
        } catch (TwitterException e) {
            logger.info(e.getMessage());
            e.printStackTrace();
        }
        
        //send(String.valueOf(posted), email);
        
        ModelAndView mav = new ModelAndView();
        mav.addObject("output", String.valueOf(posted));
        return mav;
    }
    
    public String change2Href(String text) {
        String regex = "(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(text);

        while (m.find()) {
            String find = m.group();
            text = text.replace(find, "<a href=\"" + find + "\">" + find + "</a>");
        }
        return text;
    }
    
    public void send(String msg, String email) throws IOException {
        String path = notifierPath + URLEncoder.encode(msg, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8");
       
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);
        connection.connect();
        logger.info(String.valueOf(connection.getResponseCode()));
    }
}
